package com.citicpub_cloud.restfull.utils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.DefaultValueProcessor;
import net.sf.json.processors.JsonValueProcessor;
import net.sf.json.util.JSONUtils;

/**
 * json 工具类
 *
 */
public class JsonUtil {

    //不属于JavaBean自身的属性
    private static final String NOFIELDNAME = "serialVersionUID";

    private static  JsonConfig jsonConfig;
    private static  JsonConfig jsonConfig1;
    static{
        jsonConfig = new JsonConfig();
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonConfig.setJsonPropertyFilter(new AnnotationJsonIgnoreFilter());

        jsonConfig1 = new JsonConfig();
        jsonConfig1.registerJsonValueProcessor(Date.class, new JsonDate2LongValueProcessor());
        jsonConfig1.registerJsonValueProcessor(String.class, new JsonValueProcessor() {
            @Override
            public Object processArrayValue(Object o, JsonConfig jsonConfig) {
                return process(o);
            }

            @Override
            public Object processObjectValue(String s, Object o, JsonConfig jsonConfig) {
                return process(o);
            }

            private Object process(Object value){
                if (value instanceof String) {
                    return value == null ? "" : value.toString();
                }
                return value;
            }
        });
        jsonConfig.registerJsonValueProcessor(String.class, new JsonValueProcessor() {
            @Override
            public Object processArrayValue(Object o, JsonConfig jsonConfig) {
                return process(o);
            }

            @Override
            public Object processObjectValue(String s, Object o, JsonConfig jsonConfig) {
                return process(o);
            }

            private Object process(Object value){
                if (value instanceof String) {
                    return value == null ? "" : value.toString();
                }
                return value;
            }
        });
        jsonConfig1.setJsonPropertyFilter(new AnnotationJsonIgnoreFilter());

        jsonConfig.registerDefaultValueProcessor(Integer.class,new DefaultValueProcessor() {
            @Override
            public Object getDefaultValue(Class aClass) {
                return null;
            }
        });
        jsonConfig.registerDefaultValueProcessor(Long.class, new DefaultValueProcessor() {
            @Override
            public Object getDefaultValue(Class aClass) {
                return null;
            }
        });
        jsonConfig.setJavaPropertyFilter(new NullJavaIgnoreFilter());
        JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher("yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"));
    }

    /**
     * objectToJson(java对象转json格式) (这里描述这个方法适用条件 – 可选)
     *
     * @param data
     * @return String
     * @exception
     * @since 1.0.0
     */
    public static String objectToJson(final Object data) {
        String jsonString = null;
        try {
        	if(null!=data && data instanceof List){
        		JSONArray jsonArray = JSONArray.fromObject(data,jsonConfig);
        		return jsonArray.toString();
        	}
            //日期转转json时由于是以长整型输出，因此这里注册自定义的日期转换类
            jsonString = JSONObject.fromObject(data,jsonConfig).toString();
            return jsonString;
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
    
    /*public static void main(String[] args){
    	List<Long> dd= new ArrayList<Long>();
    	dd.add(Long.valueOf(1));
    	dd.add(Long.valueOf(2));
    	
    	UserInfoDetail u = new UserInfoDetail();
    	u.setId(Long.valueOf(1));
    	u.setUserName("dlm1");
    	u.setCreateDate(new Date());
    	UserInfoDetail u2 = new UserInfoDetail();
    	u2.setId(Long.valueOf(2));
    	u2.setUserName("dlm2");
    	List<UserInfoDetail> list = new ArrayList<UserInfoDetail>();
    	list.add(u);
    	list.add(u2);
    	String ss = JsonUtil.objectToJson(dd);
    	System.out.println(ss);
    	List<Long> retList = JsonUtil.jsonToListObject(ss,Long.class);
    	for(UserInfoDetail ud:retList){
    		System.out.println("--"+ud.getUserName());
    	}
    }*/
    
    /**
     * 对象转换为json ，日期格式会转换为长整型
     * @param data
     * @return
     */
    public static String objectDateToLongJson(final Object data) {
    	String jsonString = null;
    	try {
    		if(null!=data && data instanceof List){
        		JSONArray jsonArray = JSONArray.fromObject(data,jsonConfig1);
        		return jsonArray.toString();
        	}
    		//日期转转json时由于是以长整型输出，因此这里注册自定义的日期转换类
    		jsonString = JSONObject.fromObject(data,jsonConfig1).toString();
    		return jsonString;
    	} catch (Exception e) {
    		throw new IllegalArgumentException(e);
    	}
    }

    /**
     * jsonToObject(json格式转java对象) (这里描述这个方法适用条件 – 可选)
     *
     * @param json
     * @param clazz
     * @return Object
     * @exception
     * @since 1.0.0
     */
    public static <T> T jsonToObject(final String json,Class<T> clazz) {
        try {
            JSONObject obj = JSONObject.fromObject(json,jsonConfig);
            return (T)JSONObject.toBean(obj,clazz.newInstance(),jsonConfig);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }
    
    public static <T> List<T> jsonToListObject(final String json,Class<T> clazz) {
    	try {
    		if(StringUtils.isBlank(json) || !(json.startsWith("[") && json.endsWith("]"))){
    			return Collections.emptyList();
    		}
        	 JSONArray jsonArray = JSONArray.fromObject(json,jsonConfig);
        	 List<T> retList = new ArrayList<T>();
        	 for(int i=0;i<jsonArray.size();i++){
        		 Object obj = jsonArray.get(i);
        		 if(clazz.getClass().equals(Long.class.getClass())){
        			 retList.add((T) Long.valueOf(obj.toString()));
        		 }else if(clazz.getClass().equals(String.class.getClass())){
        			 retList.add((T)obj.toString());
        		 }else if(clazz.getClass().equals(Integer.class.getClass())){
        			 retList.add((T)Integer.valueOf(obj.toString()));
        		 }else{
        			 JSONObject jobj = (JSONObject) obj;
        			 T t = (T) JSONObject.toBean(jobj,clazz.newInstance(),jsonConfig);
        			 retList.add(t);
        		 }
        	 }
        	 return retList;
    	} catch (Exception e) {
    		throw new IllegalArgumentException(e);
    	}
    }

   /* public static <T> T jsonObject2Bean(JSONObject jsonObject,Class<T> clazz){
        if(null!=jsonObject && jsonObject.size()>0){
            Map props = JSONUtils.getProperties(jsonObject);
            for( Iterator entries = jsonObject.names( jsonConfig ).iterator(); entries.hasNext(); ){
                String name = (String) entries.next();
                Class type = (Class) props.get( name );
                Object value = jsonObject.get( name );
                clazz.GET
            }
        }
    }*/


    public static Object getFieldValueByName(String fieldName, Object obj){
        try {
            String firstLetter = fieldName.substring(0,1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = obj.getClass().getMethod(getter);
            Object value = method.invoke(obj);
            return value;
        } catch (Exception e){
            return null;
        }
    }

}
